package org.angelica.modules.common;

import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.angelica.common.AppConstant;
import org.angelica.core.common.AccessToken;
import org.angelica.core.response.ResponseResult;
import org.angelica.utils.common.ToolUtil;
import org.angelica.utils.id.IdGeneratorUtil;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author aizhimin
 */
@Api(tags = {"通用"})
@RestController
@RequestMapping(value="/api/common")
public class CommonController {
    /**
     * 构建请求头公共参数
     * @param hsRequest
     * @return
     */
    @ApiIgnore
    @PostMapping(value="buildRequestHeader")
    public ResponseResult buildRequestHeader(HttpServletRequest hsRequest) {
        Map<String,String> paramMap = Maps.newHashMap();
        Enumeration<String> enu = hsRequest.getParameterNames();
        while(enu.hasMoreElements()) {
            String paramName = enu.nextElement();
            paramMap.put(paramName, hsRequest.getParameter(paramName));
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = IdGeneratorUtil.getRandomUuid();
        paramMap.put("timestamp", timestamp);
        paramMap.put("nonce", nonce);

        String sign = ToolUtil.sign(AppConstant.APP_ID, AppConstant.APP_SECRET, paramMap);
        Map<String,Object> headerMap = new HashMap<>(3);
        headerMap.put("timestamp", timestamp);
        headerMap.put("nonce", nonce);
        headerMap.put("sign", sign);
        return ResponseResult.success(headerMap);
    }

    /**
     * 构建请求头 accessToken
     * @param userId
     * @return
     */
    @ApiIgnore
    @GetMapping("/buildAccessToken")
    public ResponseResult buildAuthorization(@RequestParam(value = "userId") Long userId) {
        AccessToken accessToken = AccessToken.buildAccessToken(userId,
                AppConstant.JWT_SECRET,AppConstant.JWT_ISUSER);
        return ResponseResult.success("accessToken", accessToken);
    }

    /**
     * 初始化接口
     * @return
     */
    @ApiOperation(value = "初始化接口",notes = "系统初始化接口")
    @GetMapping(value="init")
    public ResponseResult init() {
        return ResponseResult.success()
                .put("timestamp",System.currentTimeMillis()/1000);
    }

}
